package com.wxsm.wechat.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.imageio.ImageIO;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * Created with Yang Huan
 * Date: 2017/5/26
 * Time: 14:42
 */
public class ImageUtil {

    private static final Logger logger = LoggerFactory.getLogger(ImageUtil.class);

    public static byte[] transImageSize(InputStream inputStream, String filenameExtension, int nw) {
        ByteArrayOutputStream bs = new ByteArrayOutputStream();
        try {
            AffineTransform transform = new AffineTransform();
            BufferedImage bis = ImageIO.read(inputStream); //读取图片
            int w = bis.getWidth();
            int h = bis.getHeight();
            int nh = (nw * h) / w;
            double sx = (double) nw / w;
            double sy = (double) nh / h;
            transform.setToScale(sx, sy); //将此变换设置为缩放变换。
            AffineTransformOp ato = new AffineTransformOp(transform, null);
            BufferedImage bid = new BufferedImage(nw, nh, BufferedImage.TYPE_3BYTE_BGR);
            ato.filter(bis, bid);
            ImageIO.write(bid, filenameExtension, bs);
        } catch (IOException e) {
            logger.error("图片压缩失败", e);
        }
        return bs.toByteArray();
    }

}
